//
//  ViewController.m
//  dfdsf
//
//  Created by dllo on 16/1/24.
//  Copyright © 2016年 dilo. All rights reserved.
//

#import "ViewController.h"
#import "PagForGameOfMatch.h"
#import "PageForGameOfMy.h"
#import "CellForHot.h"
#import "NetworkHandle.h"
#import "ModelForHot.h"
#import "DetailsViewController.h"
#import "DataDetailsController.h"
#import <DKNightVersion.h>
#import "CellForHot2.h"
#import "CellForHot3.h"
#import "CellForHotNone.h"
#import "CellforSpecial.h"
#import <MJRefresh.h>
#import "NetworkingHandlerOfBlock.h"
#import <AFNetworking.h>
#import "SXColorGradientView.h"
#import "UIColor+Wonderful.h"


#define WEIGHT  self.view.frame.size.width
#define HEIGHT  self.view.frame.size.height

#define WEIGHTT [UIScreen mainScreen].bounds.size.width / 375
#define HEIGHTT [UIScreen mainScreen].bounds.size.height / 667

@interface ViewController ()<UITableViewDelegate, UITableViewDataSource, NetworkHandleDelegate>
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *array;
@property (nonatomic, retain) UIButton *button;
@property (nonatomic, retain) NSMutableArray *refreshArr;
@property (nonatomic, retain) NSMutableArray *preArr;
@property (nonatomic, retain) NSMutableArray *arrDict;
@property (nonatomic, assign) BOOL net;
@property (nonatomic, retain)NSMutableArray *arrNet;
@property (nonatomic, retain)UISegmentedControl *seg;

@end

@implementation ViewController

-(void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"pleaseHide" object:nil];
     [[NSNotificationCenter defaultCenter] removeObserver:self name:@"apper" object:nil];
    [_tableView release];
    [_array release];
    [_button release];
    [_refreshArr release];
    [_preArr release];
    [_arrDict release];
    [_arrNet release];
    [_seg release];
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.seg.hidden = NO;
    self.navigationController.navigationBar.alpha = 1;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    [self handleData];
    [self createSegment];
    [self createTopButton];
    [self createTableView];
    [self createHeard];
    [self createFoot];
    [self nsnotificenter];
    
    
}

- (void)nsnotificenter {
    
    // 当点击不同的比赛的图标时让 seg 隐藏
    [[NSNotificationCenter defaultCenter] addObserverForName:@"pleaseHide" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        
        self.seg.hidden = YES;
        
    }];
    
    [[NSNotificationCenter defaultCenter] addObserverForName:@"apper" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        
        self.seg.hidden = NO;
        
    }];
    
    
    
    
}



#pragma mark - 创建头部 segmentController
- (void)createSegment {
    
    self.navigationController.navigationBar.dk_barTintColorPicker = DKColorWithColors([UIColor deepSkyBlue], [UIColor lightGrayColor]);
    self.navigationController.navigationBar.tintColor = [UIColor redColor];
    
    // 比赛界面三个头部的 segment
    self.seg = [[UISegmentedControl alloc] initWithItems:@[@"赛事", @"热门", @"我的"]];
    
    
    self.seg.frame = CGRectMake(50 * WEIGHTT, 8 * HEIGHTT, WEIGHT - 100 * WEIGHTT , 30 *HEIGHTT);
    [self.navigationController.navigationBar addSubview:self.seg];
    
    [_seg release];
    //设置默认选中的 item 为热门
    self.seg.selectedSegmentIndex = 1;
    
    //去掉颜色,现在整个segment都看不见
    self.seg.tintColor = [UIColor clearColor];
    // 设置选中时候的 segment 的属性
    NSDictionary* selectedTextAttributes = @{NSFontAttributeName:[UIFont systemFontOfSize:16],NSForegroundColorAttributeName: [UIColor redColor]};
    [self.seg setTitleTextAttributes:selectedTextAttributes forState:UIControlStateSelected];
    
    // 当 segment 没有被选中的时候的属性
    NSDictionary* unselectedTextAttributes = @{NSFontAttributeName:[UIFont systemFontOfSize:16],NSForegroundColorAttributeName:[UIColor whiteColor]};
    [self.seg setTitleTextAttributes:unselectedTextAttributes forState:UIControlStateNormal];
    
    // 为 segment 添加点击事件
    [self.seg addTarget:self action:@selector(segAction:) forControlEvents:UIControlEventValueChanged];
    
}

#pragma mark - segAction的点击事件
- (void)segAction:(UISegmentedControl *)seg {
    
    PagForGameOfMatch *match = [[PagForGameOfMatch alloc] init];
    
    PageForGameOfMy *myView = [[PageForGameOfMy alloc] init];
    
    self.navigationController.viewControllers = @[self, match,myView];
    
    [match release];
    [myView release];
    
    //通过 segment下标不同的值推出不同 vc
    switch (seg.selectedSegmentIndex) {
        case 0:
        {
            
            UIViewController *viewC = [self.navigationController.viewControllers objectAtIndex:1];
            
            [self.navigationController popToViewController:viewC animated:NO];
            
            break;
        }
        case 1:
            
            [self.navigationController popToRootViewControllerAnimated:NO];
            
            break;
            
        default:
        {
            
            UIViewController *viewC = [self.navigationController.viewControllers objectAtIndex:2];
            
            [self.navigationController popToViewController:viewC animated:NO];
            
            
            break;
        }
    }
    
}

#pragma mark - 创建 tabView

- (void)createTableView {
    
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [_tableView release];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    
    
    // 注册
    [self.tableView registerClass:[CellForHot class] forCellReuseIdentifier:@"poolForHot"];
    [self.tableView registerClass:[CellForHot2 class] forCellReuseIdentifier:@"poolForHot2"];
    [self.tableView registerClass:[CellForHot3 class] forCellReuseIdentifier:@"poolForHot3"];
    [self.tableView registerClass:[CellForHotNone class] forCellReuseIdentifier:@"poolForNone"];
    [self.tableView registerClass:[CellforSpecial class] forCellReuseIdentifier:@"poolForSpecial"];
    
}

#pragma mark - 数据处理
- (void)handleData {
    
    NSString *str = @"http://client.mix.sina.com.cn/api/match_extra/get?app_key=2586208540&_version__=3.2.1.01&__os__=android&_sport_t_=livecast&show_extra=1&f=livecast_id,LeagueType,status,Team1Id,Team2Id,Score1,Score2,MatchId,LiveMode,Discipline,data_from,Title,date,time,Team1,Team2,Flag1,Flag2,NewsUrl,VideoUrl,LiveUrl,LiveStatusExtra,VideoLiveUrl,VideoBeginTime,narrator,LeagueType_cn,Discipline_cn,comment_id,odds_id,VideoEndTime,if_rotate_video,LiveStatusExtra_cn,m3u8,android,period_cn,program,penalty1,media_tag,penalty1,Round_cn,extra,rec_ovx,VideoId&_sport_a_=hotMatches";
    
    NSString *temp = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    //调用封装好的类,解析网络数据
    
    [NetworkHandle handlerJSONWitURL:temp delegate:self];
    
}

- (void)handleDidComplete:(id)result {
    
    self.array = [NSMutableArray array];
    
    NSDictionary *dic = [result objectForKey:@"result"];
    
    NSDictionary *dic2 = [dic objectForKey:@"data"];
    NSArray *arrForFull = [dic2 objectForKey:@"full"];
    for (NSDictionary *dicT in arrForFull) {
        
        ModelForHot *model = [[ModelForHot alloc] init];
        
        [model setValuesForKeysWithDictionary:dicT];
        [self.array addObject:model];
        [model release];
        
    }
    
    // [self createTableView];
    
    [self.tableView reloadData];
    
}

/**下拉加载正在进行的比赛*/
- (void)createHeard {
    
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        //  self.array = [NSMutableArray array];
        
        [self handleData2];
        
    }];
    
    self.tableView.mj_header = header;
    
}

/** 上拉加载未进行的比赛 */

- (void)createFoot {
    
    
    MJRefreshAutoNormalFooter *foot = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        [self handleData3];
        
        
    }];
    
    
    self.tableView.mj_footer = foot;
    
}

/**下拉刷新的数据处理*/
-(void)handleData2 {
    
    NSString *str = @"http://client.mix.sina.com.cn/api/match_extra/get?app_key=2586208540&_version__=3.2.1.01&__os__=android&_sport_t_=livecast&show_extra=1&f=livecast_id,LeagueType,status,Team1Id,Team2Id,Score1,Score2,MatchId,LiveMode,Discipline,data_from,Title,date,time,Team1,Team2,Flag1,Flag2,NewsUrl,VideoUrl,LiveUrl,LiveStatusExtra,VideoLiveUrl,VideoBeginTime,narrator,LeagueType_cn,Discipline_cn,comment_id,odds_id,VideoEndTime,if_rotate_video,LiveStatusExtra_cn,m3u8,android,period_cn,program,penalty1,media_tag,penalty1,Round_cn,extra,rec_ovx,VideoId&_sport_a_=hotMatches";
    
    
    [NetworkingHandler networkingWithUrl:str completeHandle:^(NSURLResponse *response, NSData *data, id result) {
        
        self.refreshArr = [NSMutableArray array];
        NSDictionary *dic = [result objectForKey:@"result"];
        
        NSDictionary *dic2 = [dic objectForKey:@"data"];
        NSArray *arrForFull = [dic2 objectForKey:@"cur"];
        
        
        for (NSDictionary *dicT in arrForFull) {
            
            ModelForHot *model = [[ModelForHot alloc] init];
            [model setValuesForKeysWithDictionary:dicT];
            [self.refreshArr addObject:model];
            [model release];
            
        }
        //NSLog(@"%ld", self.array.count);
        [self.tableView reloadData];
        
        [self.tableView.mj_header endRefreshing];
        
    }];
    
}
/** 上拉加载的数据处理*/
- (void)handleData3 {
    
    
    NSString *str = @"http://client.mix.sina.com.cn/api/match_extra/get?app_key=2586208540&_version__=3.2.1.01&__os__=android&_sport_t_=livecast&show_extra=1&f=livecast_id,LeagueType,status,Team1Id,Team2Id,Score1,Score2,MatchId,LiveMode,Discipline,data_from,Title,date,time,Team1,Team2,Flag1,Flag2,NewsUrl,VideoUrl,LiveUrl,LiveStatusExtra,VideoLiveUrl,VideoBeginTime,narrator,LeagueType_cn,Discipline_cn,comment_id,odds_id,VideoEndTime,if_rotate_video,LiveStatusExtra_cn,m3u8,android,period_cn,program,penalty1,media_tag,penalty1,Round_cn,extra,rec_ovx,VideoId&_sport_a_=hotMatches";
    
    
    [NetworkingHandler networkingWithUrl:str completeHandle:^(NSURLResponse *response, NSData *data, id result) {
        
        NSDictionary *dic = [result objectForKey:@"result"];
        NSDictionary *dic2 = [dic objectForKey:@"data"];
        NSArray *arrForFull = [dic2 objectForKey:@"pre"];
        for (NSDictionary *dicT in arrForFull) {
            
            ModelForHot *model = [[ModelForHot alloc] init];
            [model setValuesForKeysWithDictionary:dicT];
            [self.array addObject:model];
            [model release];
            
        }
        //NSLog(@"%ld", self.array.count);
        [self.tableView reloadData];
        
        [self.tableView.mj_footer endRefreshing];
        self.tableView.mj_footer = nil;
        
    }];
    
}

#pragma mark - 创建屏幕下方可以回到最上部的 button
- (void)createTopButton {
    
    self.button = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.button setImage:[UIImage imageNamed:@"iconfont-dingbu"] forState:UIControlStateNormal];
    [self.button addTarget:self action:@selector(topAction:) forControlEvents:UIControlEventTouchUpInside];
    
}

/** 当 tableview滑动的时候调用此方法*/
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    self.button.frame  = CGRectMake(320 * WEIGHTT, self.tableView.contentOffset.y + 570 * HEIGHTT, 40 * WEIGHTT, 40 * HEIGHTT);
    [self.tableView addSubview:self.button];
    
}


- (void)topAction:(UIButton *) button {
    // 当点击 button 回到顶部
    [self.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    
    if (section == 1) {
        
        return self.array.count;
        
        
    }else {
        
        // 下拉加载正在进行的比赛的分区
        
        if (self.refreshArr.count == 0) {
            
            return 0;
            
        } else {
            
            
            return self.refreshArr.count;
            
        }
        
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    
    if (indexPath.section == 0 ) {
        
        ModelForHot *hotModel = [self.refreshArr objectAtIndex:indexPath.row];
        
        CellForHotNone *cell = [tableView dequeueReusableCellWithIdentifier:@"poolForNone"];
        [cell passModelForHot:hotModel];
        
        return cell;
        
    } else {
        
        
        if (indexPath.row < 5) {
            self.button.hidden = YES;
        }else {
            
            self.button.hidden = NO;
            
        }
        
        
        ModelForHot *model = [self.array objectAtIndex:indexPath.row];
        // cell赋值
        
        if ([model.status isEqualToString:@"3"]) {
            
            
            if (model.extra.count == 0 ) {
                if ([model.Score1 isEqualToString:@""]) {
                    
                    CellforSpecial *cell = [tableView dequeueReusableCellWithIdentifier:@"poolForSpecial"];
                    
                    [cell passModelForHot:model];
                    
                    return cell;
                    
                }else{
                    
                    CellForHotNone *cell = [tableView dequeueReusableCellWithIdentifier:@"poolForNone"];
                    [cell passModelForHot:model];
                    
                    return cell;
                }
            } else if (model.extra.count == 1) {
                
                CellForHotNone *cell = [tableView dequeueReusableCellWithIdentifier:@"poolForHot3"];
                [cell passModelForHot:model];
                
                return cell;
                
                
            } else if (model.extra.count == 2) {
                
                CellForHotNone *cell = [tableView dequeueReusableCellWithIdentifier:@"poolForHot2"];
                [cell passModelForHot:model];
                
                return cell;
                
                
            } else {
                
                CellForHot *cell = [tableView dequeueReusableCellWithIdentifier:@"poolForHot"];
                
                [cell passModelForHot:model];
                
                return cell;
            }
            
        }
        
        else {
            
            if ([model.Team1 isEqualToString:@""]) {
                
                CellforSpecial *cell = [tableView dequeueReusableCellWithIdentifier:@"poolForSpecial"];
                
                [cell passModelForHot:model];
                
                return cell;
                
                
            } else {
                CellForHotNone *cell = [tableView dequeueReusableCellWithIdentifier:@"poolForNone"];
                [cell passModelForHot:model];
                
                return cell;
            }
            
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 返回每行的高度
    
    if ([UIScreen mainScreen].bounds.size.height == 480) {
        
        if (indexPath.section == 0) {
            return ([UIScreen mainScreen].bounds.size.height - 64 - 49)  / 3.6;
        } else {
            
            ModelForHot *model = [self.array objectAtIndex:indexPath.row];
            if (model.extra.count == 3 ) {
                return ([UIScreen mainScreen].bounds.size.height - 64 - 49)  / 1.7;
                
            } else if (model.extra.count == 2) {
                
                return ([UIScreen mainScreen].bounds.size.height - 64 - 49)  / 2.1;
            }
            
            else if (model.extra.count == 1) {
                
                return ([UIScreen mainScreen].bounds.size.height - 64 - 49)  / 2.4;
            } else {
                
                return ([UIScreen mainScreen].bounds.size.height - 64 - 49)  / 3.1;
            }
            
        }
        
    } else {
        
        if (indexPath.section == 0) {
            return ([UIScreen mainScreen].bounds.size.height - 64 - 49)  / 3.6;
        } else {
            
            ModelForHot *model = [self.array objectAtIndex:indexPath.row];
            if (model.extra.count == 3 ) {
                return ([UIScreen mainScreen].bounds.size.height - 64 - 49)  / 2;
                
            } else if (model.extra.count == 2) {
                
                return ([UIScreen mainScreen].bounds.size.height - 64 - 49)  / 2.5;
            }
            
            else if (model.extra.count == 1) {
                
                return ([UIScreen mainScreen].bounds.size.height - 64 - 49)  / 2.9;
            } else {
                
                return ([UIScreen mainScreen].bounds.size.height - 64 - 49)  / 3.4;
            }
            
        }
        
        
        
    }
    
    
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    self.seg.hidden = YES;
    
    DetailsViewController *details = [[DetailsViewController alloc] init];
    
    ModelForHot *model = [self.array objectAtIndex:indexPath.row];
    NSString *str = @"http://platform.sina.com.cn/sports_all/client_api?app_key=2586208540&_version__=3.2.1.01&__os__=android&_sport_t_=livecast&_sport_a_=getMatch&id=";
    details.urling = [str stringByAppendingFormat:@"%@", model.livecast_id];
    details.ID = model.livecast_id;
    
    [self.navigationController pushViewController:details animated:YES];
    
    //[details release];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
